// @ts-ignore
const utils = require('./utils');
const config = require('./config');
const baseConfig = require('./webpack.base.conf');

// const zlib = require('zlib');
const webpack = require('webpack');
const { merge } = require('webpack-merge');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const {
  CleanWebpackPlugin
} = require('clean-webpack-plugin');
const ChunkRenamePlugin = require('webpack-chunk-rename-plugin'); // 解决开启runtimeChunk，filename问题
const productionSourceMap = config.build.productionsourcemap;
const chunkhash = config.build.chunkhash;
// 压缩css插件
const optimizeCSSPlugin = new (require('optimize-css-assets-webpack-plugin'))({
  cssProcessorOptions: productionSourceMap ? {
    safe: true,
    map: {
      inline: false
    }
  } : {
    safe: true,
    autoprefixer: {
      remove: false
    }
  }
});

// 压缩js代码插件
const UglifyJsPlugin = new (require('uglifyjs-webpack-plugin'))({
  uglifyOptions: {
    ecma: 5,
    ie: true,
    output: {
      comments: false,
      beautify: false,
      ie: true
    },
    compress: {
      pure_funcs: ['console.debug'], // 删除此类函数
      toplevel: true,
      ie: true,

      // warnings: false,
      drop_debugger: true,
      drop_console: true
    },
    mangle: {
      toplevel: true,
      eval: true,
      ie: true
    }
  },
  sourceMap: productionSourceMap,
  parallel: true
});

let webpackConfig = merge(baseConfig, {
  mode: 'production',
  module: {
    rules: utils.styleLoaders({
      sourceMap: productionSourceMap,
      extract: true,
      usePostCSS: true
    })
  },
  devtool: productionSourceMap ? config.build.devtool : false,
  output: {
    filename: filename => {
      let name = filename.chunk.name;
      if (!/entry/.test(name)) {
        name = `js/${name}`;
      }
      name = name.replace('js/entry', 'js')
      return utils.assetsPath(`${name}.[${chunkhash}].js`);
    }
  },
  plugins: [

    // 提取css文件到自己文件
    new MiniCssExtractPlugin({
      filename: filename => {
        let name = filename.chunk.name;
        if (!/entry/.test(name)) {
          name = `style/${name}`;
        }
        name = name.replace('js/entry', 'style');
        return utils.assetsPath(`${name}.[${chunkhash}].css`);
      }
    }),

    // keep module.id stable when vendor modules does not change
    new webpack.ids.HashedModuleIdsPlugin(),

    // enable scope hoisting
    new webpack.optimize.ModuleConcatenationPlugin(),

    // 拷贝静态资源
    new CopyWebpackPlugin({
      patterns: [
        {
          context: utils.resolve('src/static'), // 上下文决定拷贝位置
          from: utils.resolve('src/static/images/**/*.*'),
          to: utils.assetsPath('[path][name][ext]')
        },
        {
          context: utils.resolve('src/static'), // 上下文决定拷贝位置
          from: utils.resolve('src/static/fonts/**/*.{eot,svg,ttf,woff,woff2}'),
          to: utils.assetsPath('[path][name][ext]'),
        },
      ],

    }),
    new ChunkRenamePlugin({
      initialChunksWithEntry: true
    }),
    new CleanWebpackPlugin()
  ],

  // 将供JS公共提取到public文件中
  optimization: {
    minimizer: [UglifyJsPlugin, optimizeCSSPlugin],
    splitChunks: {
      cacheGroups: {
        default: false,
        vendors: {
          name: 'vendor',
          priority: 10,
          chunks: 'initial',
          minChunks: 2
        }
      }
    },
    runtimeChunk: {
      name: 'manifest'
    }
  }

});

if (config.build.productionGzip) {
  const CompressionWebpackPlugin = require('compression-webpack-plugin');

  webpackConfig.build.plugins.push(
    new CompressionWebpackPlugin({

      // @ts-ignore
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  );
}

// 是否打开analyzer报告
if (config.build.bundleAnalyzerReport) {
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
  webpackConfig.build.plugins.push(new BundleAnalyzerPlugin());
}
module.exports = webpackConfig;
